﻿using System.Collections.Generic;
using System.Linq;
using System.Web;
using Inscriptionem.Services;

namespace Inscriptionem.Localization
{
    public class Language
    {
        protected const string LanguageSessionToken = "Language";
        public static Language Current
        {
            get
            {
                if (HttpContext.Current.Session == null)
                {
                    return new Language();
                }

                var language = HttpContext.Current.Session[LanguageSessionToken] as Language;
                if (language == null)
                {
                    language = new Language();
                    HttpContext.Current.Session[LanguageSessionToken] = language;
                }
                return language;
            }
            set { HttpContext.Current.Session[LanguageSessionToken] = value; }
        }

        protected string value;
        public string Value
        {
            get
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    return value = DefaultValue;
                }

                return value.Length == 1 ? value.ToUpper() : value.Substring(0, 1).ToUpper() + value.Substring(1).ToLower();
            }

            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    this.value = DefaultValue;
                    return;
                }

                var language = AllowedValues.FirstOrDefault(l => l.Name.ToLower() == value.ToLower());
                if (language != null)
                {
                    this.value = language.Name;
                    return;
                }

                this.value = DefaultValue;
            }
        }

        public static string DefaultValue
        {
            get
            {
                var languages = AllowedValues;
                var language = languages.FirstOrDefault(l => l.IsDefault) ?? languages.FirstOrDefault();
                return language == null ? string.Empty : language.Name;
            }
        }

        public static IEnumerable<ORM.Language> AllowedValues
        {
            get
            {
                if(!InstallService.IsDBAvailableAndCorrect )
                {
                    return new List<ORM.Language>();
                }
                return new ORM.DB().Languages;
            }
        }
    }
}